<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Comments_model extends CI_Model {

    private $_table_name = 'comments';

    public function __construct() {
        parent::__construct();
    }

    /**
     * 添加评论
     */
    public function create() {
        $comment = array(
            'email' => $this->input->post('email'),
            'content' => htmlspecialchars($this->input->post('content')),
            'did' => $this->input->post('did'),
            'dtype' => $this->input->post('dtype'),
            'created' => date('Y-m-d H:i:s')
        );
        $this->db->set('created', 'NOW()', FALSE);
        $this->db->insert($this->_table_name, $comment);
        $id = $this->db->insert_id();
        $this->update_count($this->input->post('did'),$this->input->post('dtype'));

        return $id;
    }

    /**
     * 获取评论列表
     * @param   int     $did 关联ID
     * @param   int     $dtype 关联类型
     * @param   int     $num 单面显示评论数量
     * @param   int     $offset 结果集偏移量
     * @return  array   
     */
    public function get_comments($did, $dtype, $num, $offset) {
        $this->db->order_by("created", "desc");
        $query = $this->db->get_where(
                        $this->_table_name, array('did' => $did, 'dtype' => $dtype), $num, $offset
        );

        return $query->result();
    }

    /**
     * 增加评论数量
     * @param   int     $did 关联ID
     * @param   int     $dtype 关联类型
     * @param   int     $operator 是增加还是减少
     */
    public function update_count($did, $dtype, $operator=1) {
        if ($dtype == 1) {
            if ($operator > 0) {
                $this->db->set('comment_count', 'comment_count + 1', FALSE);
            } else {
                $this->db->set('comment_count', 'comment_count - 1', FALSE);
            }
            $this->db->where('ID', $did);
            $this->db->update('posts');
        } elseif ($dtype == 2) {
            
        }
    }

}